import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

// 创建axios实例
const instance = axios.create({
  baseURL: 'http://localhost:8000/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response
  },
  async error => {
    if (error.response) {
      if (error.response.status === 401) {
        // token过期，尝试使用refresh token
        const refreshToken = localStorage.getItem('refresh_token')
        if (refreshToken) {
          try {
            const response = await axios.post('http://localhost:8000/api/auth/token/refresh/', {
              refresh: refreshToken
            })
            
            if (response.data.access) {
              localStorage.setItem('access_token', response.data.access)
              error.config.headers['Authorization'] = `Bearer ${response.data.access}`
              return instance(error.config)
            }
          } catch (refreshError) {
            // refresh token也过期，需要重新登录
            localStorage.removeItem('access_token')
            localStorage.removeItem('refresh_token')
            router.push('/login')
            ElMessage.error('登录已过期，请重新登录')
          }
        } else {
          router.push('/login')
          ElMessage.error('请先登录')
        }
      }
    }
    return Promise.reject(error)
  }
)

export default instance 